package com.xckj.teacher.ui.activity

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import androidx.annotation.Nullable
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.LargeValueFormatter
import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.utils.ColorTemplate
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.xckj.teacher.R
import com.xckj.teacher.databinding.ActivityHomeworkReportBinding
import com.xckj.teacher.databinding.ActivityRoomReportBinding
import com.xckj.teacher.framework.BaseActivity
import com.xckj.teacher.presenter.ClassPresenter
import com.xckj.teacher.ui.adapter.AccountAdapter
import com.xckj.teacher.ui.adapter.ClassListAdapter
import com.xckj.teacher.ui.fragment.HomeWorkFragment
import com.xckj.teacher.util.get


/**
 * 机房考试报告
 */
class RoomReportActivity : BaseActivity<ActivityRoomReportBinding>() {

    private val classListAdapter: ClassListAdapter by lazy { ClassListAdapter(arrayListOf()) }
    private val presenter: ClassPresenter by lazy { ClassPresenter(this) }
    var accountPop: PopupWindow? = null


    var selectPosition = 0
    var years = arrayListOf("2023-2024学年", "2022-2023学年", "2021-2022学年")
    var classId = ""
    var start = ""
    var end = ""
    var className = ""
    override fun setStatusBarColor(): Int {
        return R.color.white
    }

    inner class ProxyClick {
        fun back() {
            finish()
        }

        fun select() {
            val accountPopView = LayoutInflater.from(this@RoomReportActivity)
                .inflate(R.layout.account_list_dialog, null)
            accountPop = PopupWindow(
                accountPopView,
                dataBinding?.tvYear?.width ?: 0,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            var rv = accountPopView.findViewById<RecyclerView>(R.id.rv_account)
            var accountAdapter = AccountAdapter(years, selectPosition)
            rv.layoutManager = LinearLayoutManager(this@RoomReportActivity)
            rv.adapter = accountAdapter

            accountAdapter.setOnItemClickListener { baseQuickAdapter, view, i ->
                accountAdapter.select = i
                selectPosition = i
                accountAdapter.notifyDataSetChanged()
                dataBinding?.tvYear?.text = years[i]
                when (years[i]) {
                    "2023-2024学年" -> {
                        start = "2023"
                        end = "2024"
                    }

                    "2022-2023学年" -> {
                        start = "2022"
                        end = "2023"
                    }

                    "2021-2022学年" -> {
                        start = "2021"
                        end = "2022"
                    }
                }
                reportData()
                accountPop?.dismiss()
            }
            accountPop?.isFocusable = true
            if (accountPop?.isShowing == true) {
                accountPop?.dismiss()
            }
            accountPop?.showAsDropDown(dataBinding?.tvYear)
        }
    }


    override fun loadLayout(): Int {
        return R.layout.activity_room_report
    }

    override fun initData() {
        dataBinding.click = ProxyClick()

        classId = intent.get<String>("classId") ?: ""
        className = intent.get<String>("className") ?: ""

        initLineChart()

        start = "2023"
        end = "2024"
        dataBinding?.tvType?.text = "$className 机房考试报告"
        reportData()
    }

    private fun reportData() {
        presenter.machine(start, end, classId) {
            dataBinding?.tvCount?.text = "${it.count}"
            dataBinding?.tvCityExam?.text = "${it.countCity}"
            dataBinding?.tvSchoolExam?.text = "${it.countSchool}"
            dataBinding?.tvClassExam?.text = "${it.countGrade}"
            dataBinding?.tvTotalCount?.text = "${it.avgScore}"
            dataBinding?.tvTotalCityExam?.text = "${it.avgCity}"
            dataBinding?.tvTotalSchoolExam?.text = "${it.avgSchool}"
            dataBinding?.tvTotalClassExam?.text = "${it.avgGrade}"
            //            setData(it.linear.goal, it.linear.date)
            dataBinding?.table1?.removeAllViews()
            if (it.list.size != 0) {
                var tabRow1 =
                    View.inflate(this@RoomReportActivity, R.layout.item_table_row_head, null)
                dataBinding?.table1?.addView(tabRow1)
                it.list.forEach { ll ->
                    var tabRow =
                        View.inflate(this@RoomReportActivity, R.layout.item_table_row, null)
                    tabRow.findViewById<TextView>(R.id.tv_date).text = ll.date
                    tabRow.findViewById<TextView>(R.id.tv_people).text = "${ll.people}"
                    tabRow.findViewById<TextView>(R.id.tallest).text = "${ll.tallest}"
                    tabRow.findViewById<TextView>(R.id.countScore).text = "${ll.countScore}"
                    tabRow.findViewById<TextView>(R.id.goal).text = ll.goal
                    tabRow.findViewById<TextView>(R.id.average).text = ll.average
                    tabRow.findViewById<TextView>(R.id.lowest).text = "${ll.lowest}"
                    dataBinding?.table1?.addView(tabRow)
                }
            }
        }
    }

    override fun setListener() {

    }

    private fun initLineChart() {
        var mChart = dataBinding?.mChart
        mChart?.description?.isEnabled = false
        mChart?.setPinchZoom(true)
        mChart?.isScaleXEnabled = true
        mChart?.isScaleYEnabled = false
        mChart?.setDrawGridBackground(false)

        val l = mChart?.legend
        l?.verticalAlignment = Legend.LegendVerticalAlignment.TOP

        l?.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT

        l?.orientation = Legend.LegendOrientation.HORIZONTAL
        l?.setDrawInside(false)
        l?.yOffset = 0f
        l?.yEntrySpace = 0f
        l?.textSize = 8f
        l?.form = Legend.LegendForm.LINE
        l?.textColor = Color.parseColor("#FF999999")


        val leftAxis = mChart?.axisLeft
        leftAxis?.valueFormatter = LargeValueFormatter()
        leftAxis?.setDrawGridLines(true)
        leftAxis?.axisLineColor = Color.parseColor("#FFFFFF")
        leftAxis?.gridColor = Color.parseColor("#FFE5E5E5")
        leftAxis?.spaceTop = 35f
        leftAxis?.axisMinimum = 0f // this replaces setStartAtZero(true)
        mChart?.axisRight?.isEnabled = false
        mChart?.isHighlightPerTapEnabled = false
        mChart?.isHighlightPerDragEnabled = false
    }

    private fun setData(yVals1: ArrayList<String>, mLabels: List<String>) {
        val xAxis = dataBinding?.mChart?.xAxis
        xAxis?.granularity = 1f
        xAxis?.setDrawGridLines(false)
        xAxis?.position = XAxis.XAxisPosition.BOTTOM
        xAxis?.setCenterAxisLabels(false)
        xAxis?.axisMinimum = 0f


        var data = arrayListOf<Entry>()
        yVals1.forEachIndexed { i, s ->
            data.add(Entry(i.toFloat(), s.replace("%", "").toFloat()))
        }


        xAxis?.valueFormatter = object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                LogUtils.e(value)
                if (value.toInt() >= 0 && value.toInt() < mLabels.size) {
                    LogUtils.e(mLabels[value.toInt()])
                    return mLabels[value.toInt()]
                }
                return ""
            }
        }
        xAxis?.labelCount = mLabels.size
        val set1: LineDataSet
        if (dataBinding?.mChart?.data != null &&
            dataBinding?.mChart?.data?.getDataSetCount() ?: 0 > 0
        ) {
            set1 = dataBinding?.mChart?.data?.getDataSetByIndex(0) as LineDataSet
            set1.setValues(data)
            dataBinding?.mChart?.data?.notifyDataChanged()
            dataBinding?.mChart?.notifyDataSetChanged()
        } else {
            set1 = LineDataSet(data, "得分率 (%)")
            set1.setCubicIntensity(1.0f)
            set1.axisDependency = YAxis.AxisDependency.LEFT
            set1.setColor(Color.parseColor("#2979FF"))
            set1.setCircleColor(Color.parseColor("#2288FF"))
            set1.setLineWidth(2f)
            set1.circleRadius = 2.5f
            set1.setDrawFilled(true)
            set1.fillAlpha = 54
            set1.setFillColor(ColorTemplate.rgb("#FF79ABFF"))
            set1.setDrawCircleHole(true)
            val lineData = LineData(set1)
            xAxis?.setAxisMinimum(lineData.xMin - 0.5f);
            xAxis?.setAxisMaximum(lineData.xMax + 0.5f);
            dataBinding?.mChart?.setData(lineData)
            dataBinding?.mChart?.invalidate()
        }
    }

}